/*
	签约数量 (关联报价/测算/政策、合同明细变更)、
	已审批数量（合同已生效/无销售合同明细已批准反写、合同明细变更）、
	申请发货数量（发货申请点通知助理时反写）、
	已发货数量（助理点确认出库获取出库单号，并将序列号反写到发货申请仪器对照的NC仪器中）、
	已安装数量（工单完成）、
	退换机数量（退换机申请已批准）、
	可申请发货数量（=已审批数量-申请发货数量+退换机数量）


	cps 仪器合同产品的Id 
	tag 要计算的 1 2 3 4 5 6 
		//1.计算  签约数量 : Quantity__c

			//1.1 合同关联生成产品: ( 推送OA的时候 )

			//1.2 合同变更 审批通过之后(已生效) 触发: 反写到明细 明细变更数量


		//2.已审批数量 ApplicationQuantity__c
			//2.1 已生效
		    //2.2 合同变更 反写到明细 明细变更数量
			//2.3 无合同 审批通过 明细变更数量

		//3.申请发货数量:ApplyQuantity__c
		 	//3.1 发货申请 点 通知助理时反写,同步nc,作废,生成前置单据 (锁定记录 不允许修改)都要反写 
		
		//4.已发货数量 :QuantityShipped__c
			//4.1 发货申请 同步nc,作废,生成前置单据

		//5.已安装数量 InstallQuantity__c
			//5.1 合同明细-->安装申请-->工单 完成 反写

		//6.退换机数量 RefundQuantity__c
		     //6.1 退换机申请: 审批通过 



		///一 : 安装申请的前置单据自动生成
		///二 : 

*/


public without sharing class ContractCalcEquipmentUtil {
    

    // 计算退换机数量 : 退换机申请审批通过 数量反写到合同产品
	public static void returnBackToContract(String cpId){

		System.debug('returnBackToContract==>'+cpId);
		Integer rnum =  [select count()  from Return_Machine__c

		 where  Instrument__c != null and  Instrument__r.ContractInstruments__c =:cpId  
		 and ReturningWay__c not in ('退回迈克不再安装','移机-更换仪器开票客户')  ];
		
		System.debug(rnum);

		update new ContractProduct__c(Id=cpId,RefundQuantity__c = rnum );


	}

	//计算已安装数量 : 安装工单完成
	public static void installBackToContract(String cpId){
		
		Integer inNum = [select count() from InstallationApply__c   where   ContractEquipment__c =:cpId and RelatedWorkOrder__r.Status__c = '完成'  ];
		update new ContractProduct__c(Id=cpId,InstallQuantity__c = inNum );


	}


	//计算申请发货数量
	public static void sendBackToContract(String oppId){


		Map<Id,ContractProduct__c> appyNumMap = new Map<Id,ContractProduct__c>();

		for ( ContractProduct__c cp :[select Id  from ContractProduct__c where Opportunity__c =: oppId ] ) {

			appyNumMap.put(cp.Id , new ContractProduct__c(Id =cp.Id, ApplyQuantity__c = 0) );
		}

		List<InstrumentDeliverynDetails__c> tmp = [select Id ,DeliveryInstrument__c,Number__c,ReturnToMainTable__r.WarehouseReceiptTime__c ,DeliveryInstrument__r.Product__r.InstrumentType__c    from InstrumentDeliverynDetails__c 
		where DeliveryInstrument__r.Opportunity__c =:oppId and ReturnToMainTable__r.IsDisabled__c != true 
		and ( ReturnToMainTable__r.NotifiedAssistantTime__c != null Or ReturnToMainTable__r.NC__c = true  or ReturnToMainTable__r.WarehouseReceiptTime__c != null   )  ];
		
		for(InstrumentDeliverynDetails__c idd :tmp ){

			Decimal num  = idd.Number__c == null ? 0 : idd.Number__c;

			ContractProduct__c cp = appyNumMap.containsKey(idd.DeliveryInstrument__c)? appyNumMap.get(idd.DeliveryInstrument__c) : new ContractProduct__c(Id= idd.DeliveryInstrument__c);


			//申请
			cp.ApplyQuantity__c = cp.ApplyQuantity__c != null   ? cp.ApplyQuantity__c  + num : num;
			
	
			//发货 和 小型仪器的安装数
			if(   idd.ReturnToMainTable__r.WarehouseReceiptTime__c != null ){
				
				cp.QuantityShipped__c =  cp.QuantityShipped__c != null   ? cp.QuantityShipped__c  + num : num ;
				if(idd.DeliveryInstrument__r.Product__r.InstrumentType__c  =='非维保仪器' )cp.InstallQuantity__c  = cp.InstallQuantity__c != null   ? cp.InstallQuantity__c  + num : num ;
			
			}
			

			appyNumMap.put(idd.DeliveryInstrument__c, cp);
		}


	  
		if(!appyNumMap.isEmpty() )update appyNumMap.values();


	}

	//合作明细的合同
	public static void calcCoopEquipmentNum(String oppId  ){

		Map<Id,Decimal> cpNumMap = new Map<Id,Decimal>();
		


		List<ContractProduct__c> cpList = new List<ContractProduct__c>();


		for (NoContractInstrumentApplicationDetail__c nod  : [select Id ,ApplicationInstrument__c ,Number__c 

			from   NoContractInstrumentApplicationDetail__c where ApplicationInstrument__r.Contract__r.Status__c != '已生效'   and NoContractInstrumentApplication__r.stage__c='已批准' and  NoContractInstrumentApplication__r.Opportunity__c =: oppId ]) {
			
			if(nod.ApplicationInstrument__c != null && nod.Number__c != null   ){

				cpNumMap.put(nod.ApplicationInstrument__c , (cpNumMap.containsKey(nod.ApplicationInstrument__c) ? cpNumMap.get(nod.ApplicationInstrument__c) + nod.Number__c : nod.Number__c )); 
			}



		
		}

		for (Id cpId  : cpNumMap.keySet() ) {
			cpList.add(new ContractProduct__c(Id=cpId ,ApplicationQuantity__c=cpNumMap.get(cpId) ));
		}


		if(!cpList.isEmpty()) update cpList;


	}
	
	//重新计算签约数量和审批通过数量 合同生效或者 合同变更 生效
	public static void calcEquipmentNum(String  conId  ){

		//签约数量
		Map<Id,Decimal> quantityMap = new Map<Id,Decimal>();
		//已审批数量
		Map<Id,Decimal> applyMap = new Map<Id,Decimal>();


		List<ContractProduct__c> cpList = new List<ContractProduct__c>();

		for(ContractProduct__c cp : [select Id,Contract__r.Status__c,Contract__r.Stopped__c ,Quantity__c ,OriginNumber__c,ApplicationQuantity__c  from ContractProduct__c where Contract__c =:conId ]){

				if(cp.Quantity__c == null )cp.Quantity__c = cp.OriginNumber__c;
				
				cp.ApplicationQuantity__c = cp.Contract__r.Stopped__c == true ?  cp.QuantityShipped__c :  cp.Quantity__c;
				cpList.add(cp);

	
		}

		
		System.debug('ContractCalcEquipmentUtil==>'+cpList);

		if(!cpList.isEmpty()) update cpList;


	}


	//无销售合同审批通过 且 合同未生效  合同生效时已审批数量= 签约数量 
	/*public static void backToContract(String conId  ){

		Map<Id,Decimal> cpNumMap = new Map<Id,Decimal>();
		
		for (NoContractInstrumentApplicationDetail__c nod  : [select Id ,ApplicationInstrument__c ,Number__c 

			from   NoContractInstrumentApplicationDetail__c where NoContractInstrumentApplication__r.Contract__c =: conId  and NoContractInstrumentApplication__r.stage__c='已批准' and NoContractInstrumentApplication__r.Contract__r.Status__c != '已批准' ]) {
			
			if(nod.ApplicationInstrument__c != null && nod.Number__c != null   )cpNumMap.put(nod.ApplicationInstrument__c , (cpNumMap.containsKey(nod.ApplicationInstrument__c) ? cpNumMap.get(nod.ApplicationInstrument__c) + nod.Number__c : nod.Number__c )); 
		}
		List<ContractProduct__c> cpList = new List<ContractProduct__c>();

		for (ContractProduct__c cp :[select Id,ApplicationQuantity__c,Quantity__c  from ContractProduct__c where Id in:cpNumMap.keySet()] ) {
			
			if(cp.ApplicationQuantity__c == null   )cp.ApplicationQuantity__c = cpNumMap.get(cp.Id);

			if(cp.Quantity__c == null ||  cp.ApplicationQuantity__c > cp.Quantity__c  )cp.ApplicationQuantity__c = cp.Quantity__c;

			cpList.add(cp);
		}



		if(!cpList.isEmpty()) update cpList;


	}*/


	//合同变更 推送OA 反写签约数量到 原合作产品
	public static void mToOaBackToMainContract(Contract__c mcon   ){
		List<ContractProduct__c> cpList = new List<ContractProduct__c>();
		List<ContractChangeList__c> cclL = [select Id,ContractProduct__c,Product__c,ChangeQuantity__c,CooperateType__c,
			AlterType__c,AdjustSalesPrice__c,SalesPrice__c,WhetherAddInstrument__c,RelatedMeasure__c,EnterWay__c
			from ContractChangeList__c where Contract__c=: mcon.Id   ];
		for ( ContractChangeList__c ccl : cclL ) {
			ContractProduct__c cp = new ContractProduct__c();
			cp.Id = ccl.ContractProduct__c ;
		
			if(ccl.AlterType__c.contains('变更原合同仪器数量')){
			 	cp.Quantity__c = ccl.ChangeQuantity__c;
			 	cpList.add(cp);
			}
		}
		if(!cpList.isEmpty())update cpList;

	}
	public static void modifyBackToMainContract(Contract__c mcon   ){

		//获取变更明细
		List<ContractProduct__c> cpList = new List<ContractProduct__c>();

		List<ContractProduct__c> delcpList = new List<ContractProduct__c>();
		//<产品Id,变更明细>
		Map<Id,ContractChangeList__c> cclMap = new Map<Id,ContractChangeList__c>();

		List<Measure_Calculate_Product__c> mcpList = new List<Measure_Calculate_Product__c>();


		List<ContractChangeList__c> cclL = [select Id,ContractProduct__c,Product__c,ChangeQuantity__c,CooperateType__c,
			AlterType__c,AdjustSalesPrice__c,SalesPrice__c,WhetherAddInstrument__c,RelatedMeasure__c,EnterWay__c,CoopInstrumentsNew__c,CoopInstrumentsNew__r.Contract__c
			from ContractChangeList__c where Contract__c=: mcon.Id   ];//and Contract__r.IsBackToMain__c != true 

			
		for ( ContractChangeList__c ccl : cclL ) {
				ContractProduct__c cp = new ContractProduct__c();

				cp.Id = ccl.ContractProduct__c ;// ccl.AlterType__c == '新增合同仪器' ? null : ccl.ContractProduct__c
				cp.CoopType__c = ccl.CooperateType__c;
				cp.EnterWay__c = ccl.EnterWay__c;
				
			if(ccl.AlterType__c == '新增合同仪器' ){
				cp.Contract__c = mcon.MainContract__c;
				//cp.Id = ccl.ContractProduct__c ;
				cp.Quantity__c = ccl.ChangeQuantity__c;
				cp.OriginNumber__c = ccl.ChangeQuantity__c;

				cp.Product__c = ccl.Product__c;
				cp.SalesPrice__c = ccl.AdjustSalesPrice__c;
				//cp.CoopType__c = ccl.CooperateType__c;
				cp.ApplicationQuantity__c = ccl.ChangeQuantity__c;
				/*
				cclMap.put(cp.Product__c, ccl);
				//将测算的仪器挂在简易测算下面
				if(ccl.WhetherAddInstrument__c =='是' &&ccl.RelatedMeasure__c !=  null ){
					Measure_Calculate_Product__c mcp = new 	Measure_Calculate_Product__c();
					mcp.Measure_Calculate__c = ccl.RelatedMeasure__c;
					mcp.Product__c = ccl.Product__c;
					mcp.Quantity__c = ccl.ChangeQuantity__c;
					mcp.IsEquipRelated__c = true;
					mcpList.add(mcp);

				}
				*/

			}
			 if(ccl.AlterType__c == '减少原合同仪器数量' ){

				cp.Quantity__c = ccl.ChangeQuantity__c;
				cp.OriginNumber__c = ccl.ChangeQuantity__c;

				cp.ApplicationQuantity__c  = ccl.ChangeQuantity__c;
				//if(ccl.ChangeQuantity__c == 0 )cp.Status__c ='失效';

			}
			if(ccl.AlterType__c == '合作形式/价格变更'){
				ContractProduct__c cp1 = new ContractProduct__c(Id=ccl.CoopInstrumentsNew__c )  ;
				cp1.Status__c = '失效';
				cpList.add(cp1);
				cp.Contract__c = ccl.CoopInstrumentsNew__r.Contract__c;
			}
			//  if(ccl.AlterType__c.contains('变更原合同仪器报价')){

			// 	cp.SalesPrice__c = ccl.AdjustSalesPrice__c;

			// }


			cpList.add(cp);

		}

		//if(!delcpList.isEmpty()) delete delcpList;

		if(!cpList.isEmpty())upsert cpList;
		/*System.debug('ContractCalcEquipmentUtil==>'+cpList);

		List<ContractChangeList__c> cclList =new List<ContractChangeList__c>();
		for (ContractProduct__c cp : cpList) {
			ContractChangeList__c ccl = cclMap.get(cp.Product__c);
			if(ccl == null)continue;
			 ccl.ContractProduct__c = cp.Id;
			 cclList.add(ccl);

		}
		if(!cclList.isEmpty()) update cclList;

		if(!mcpList.isEmpty()) insert mcpList;
		update new Contract__c(Id =mcon.Id  ,IsBackToMain__c = true );
		*/

		//审批通过 重新计算 主合同的审批数量
		//if(mcon.MainContract__c != null  && isPass) calcEquipmentNum(mcon.MainContract__c);
		//System.debug('ContractCalcEquipmentUtil==>'+cclList);

		//System.debug('ContractCalcEquipmentUtil==>'+mcpList);

	}

	 

}